$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
  var mstform = $NG.getCmpApi("p_form_Milestone_Plan_m"); //里程碑计划主表

  var dgrid1 = $NG.getCmpApi("p_form_Milestone_Plan_d"); //里程碑计划明细
  var dgrid2 = $NG.getCmpApi("p_form_Milestone_Task_d"); //里程碑任务明细
  var dgrid3 = $NG.getCmpApi("p_form_Milestone_Repay_d"); //里程碑回款明细
  var dgrid4 = $NG.getCmpApi("p_form_Construction_plan"); //施工计划
  var dgrid5 = $NG.getCmpApi("p_form_Income_Plan"); //收入计划
  var dgrid6 = $NG.getCmpApi("p_form_Unconverted_Income"); //未转化收入分析

  const toolbar = $NG.getCmpApi("toolbar");
  const toolbar_top = $NG.getCmpApi("toolbar_top");
  const dtoolbar1 = $NG.getCmpApi("toolbar_p_form_Milestone_Plan_d");
  const dtoolbar2 = $NG.getCmpApi("toolbar_p_form_Milestone_Task_d");
  const dtoolbar3 = $NG.getCmpApi("toolbar_p_form_Milestone_Repay_d");
  const dtoolbar4 = $NG.getCmpApi("toolbar_p_form_Construction_plan");
  const dtoolbar5 = $NG.getCmpApi("toolbar_p_form_Income_Plan");
  console.log(toolbar_top);
  console.log($NG.getPageUI());
  console.log($NG.getPageState());

  ////////////////////////////////////////////////////////////////////////////////////////////////////toolbar
  try {
    toolbar.getItem("imp_push").setProps({
      children: "里程碑变更",
    });
  } catch (err) {}
  const toolbars = [
    { toolbar: toolbar, items: ["imp_push_his", "impinfoview", "batchExportOfAttachments"] },
    { toolbar: toolbar_top, items: ["imp", "impinfoview", "imp_push_his"] },
    { toolbar: dtoolbar1, items: ["addrow", "imp", "attachment"] },
    { toolbar: dtoolbar2, items: ["addrow", "imp", "attachment"] },
    { toolbar: dtoolbar3, items: ["imp", "attachment"] },
    { toolbar: dtoolbar4, items: ["imp", "attachment"] },
    { toolbar: dtoolbar5, items: ["imp", "attachment"] },
  ];
  toolbars.forEach(({ toolbar, items }) => {
    if (toolbar && typeof toolbar.getItem === "function") {
      items.forEach((item) => {
        const button = toolbar.getItem(item);
        if (button) {
          button.setHidden(); // 隐藏按钮
        }
      });
    }
  });

  // 隐藏
  const hideArrKey = ["u_fund_name", "amt"];
  hideArrKey.forEach((item) => {
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_Milestone_Task_d[item].setProps({
        hidden: true,
      });
    });
  });

  if (dtoolbar1) {
    dtoolbar1.insert({
      id: "addMilestone",
      text: "新增里程碑",
      iconCls: "icon-New",
    });
    useClick(async function ({ args }) {
      addMilestone();
    }, "addMilestone");
  }
  if (dtoolbar2) {
    dtoolbar2.insert({
      id: "addMilestoneTask",
      text: "新增里程碑任务",
      iconCls: "icon-New",
    });
    //   dtoolbar2.insert({
    //     id: "addRepayTask",
    //     text: "新增回款任务",
    //     iconCls: "icon-New",
    //   });
    useClick(async function ({ args }) {
      addMilestoneTaskClick();
    }, "addMilestoneTask");
    useClick(async function ({ args }) {
      addRepayTask();
    }, "addRepayTask");
  }

  if (dtoolbar4) {
    dtoolbar4.hideButton("addrow");
    dtoolbar4.hideButton("attachment");
    dtoolbar4.insert({
      id: "addConstructionPlan",
      text: "新增施工计划",
      iconCls: "icon-New",
    });
    useClick(async function ({ args }) {
      addConstructionPlan();
    }, "addConstructionPlan");
  }

  useClick(async function ({ args }) {
    setTimeout(function () {
      updateRepay();
    }, 500);
  }, "deleterow");

  ////////////////////////////////////////////////////////////////////////////////////////////////////mstform

  getPtInfoByPhid();
  mstformUpdateUI();
  // dgrid6UpdateUI();
  if (mstform) {
    if (mstform.getItem("phid_pc").getValue()) {
      getPtInfoByPhid();
      dgrid4Filter();
    }
  }

  if (page.oType == "add") {
    // dgrid6AddRows();
  }
  if (page.oType == "add" || page.oType == "copy") {
    addRepayPlan();
  }
  useValuesChange(({ args }) => {
    getPtInfoByPhid();
    addRepayPlan();
    dgrid4Filter();
  }, "p_form_Milestone_Plan_m.phid_pc");
  useValuesChange(({ args }) => {
    dgrid6UpdateUI();
  }, "p_form_Milestone_Plan_m.u_report_dt");

  ////////////////////////////////////////////////////////////////////////////////////////////////////dgrid1 里程碑计划明细
  ////////////////////////////////////////////////////////////////////////////////////////////////////p_form_Milestone_Plan_d
  useDataIndexChange(({ args, instance }) => {
    // updateRepay(dgrid2.getRows());
    getMinAndMaxDates(dgrid1.getRows())
  }, "p_form_Milestone_Plan_d.u_plan_start_dt");
  useDataIndexChange(({ args, instance }) => {
    // updateRepay(dgrid2.getRows());
    getMinAndMaxDates(dgrid1.getRows())
    dgrid3.getRows().forEach((items) => {
      if (items.u_milestone_phid == args[0].u_milestone_phid) {
        items.u_plan_end_dt = args[0].u_plan_end_dt;
        instance.updateRow(args[0]);
      }
    });
  }, "p_form_Milestone_Plan_d.u_plan_end_dt");

  ////////////////////////////////////////////////////////////////////////////////////////////////////dgrid2 里程碑任务明细
  ////////////////////////////////////////////////////////////////////////////////////////////////////p_form_Milestone_Task_d

  useDataIndexChange(({ args, instance }) => {
    updateRepay(args);
  }, "p_form_Milestone_Task_d.u_plan_start_dt");
  useDataIndexChange(({ args, instance }) => {
    updateRepay(args);
  }, "p_form_Milestone_Task_d.u_plan_end_dt");

  function handleDgrid2Update(params) {
    dgrid2.getRows().forEach(function (items) {});
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////--p_form_Milestone_Repay_d 里程碑回款明细

  // 日期计算
  function reduceDate(date, day){
    if(!date || day == undefined || day == NaN) return ""
    let dayTime = Number(day) * 24 * 3600 * 1000;
    let entTime = new Date(date).getTime() + dayTime;
    return `${new Date(entTime).getFullYear()}-${String(new Date(entTime).getMonth() + 1).padStart(2,'0')}-${String(new Date(entTime).getDate()).padStart(2,'0')}`
  }

  //找时间早晚(里程碑计划时间)
  function getMinAndMaxDates(data) {
    const formatDate = date => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
      };
    const dates = [];
    const dates1 = [];
  
    data.forEach(item => {
      if (item.u_plan_start_dt) {
        dates.push(new Date(item.u_plan_start_dt));
      }
      if (item.u_plan_end_dt) {
        dates1.push(new Date(item.u_plan_end_dt));
      }
    });
    console.log(`时间计算数组`,dates,dates1,);
    if (dates.length === 0) {
      return { min: null, max: null };
    }
    if(dates1.length === 0){
        return
    }
  
    const minDate = new Date(Math.min(...dates));
    const maxDate = new Date(Math.max(...dates1));
    console.log(`时间计算`,maxDate,{
        min: formatDate(minDate),
        max: formatDate(maxDate)
      });
  $NG.updateState((updater)=>{
    updater.data.p_form_Milestone_Plan_m.setProps({
        u_plan_start_dt:minDate,
        u_plan_end_dt:maxDate
    })
  })
  }
  
  if (dgrid3) {
    console.log("dgrid3存在:p_form_Milestone_Repay_d");
    useDataIndexChange(({ args, instance }) => {
      dgrid1.getData().forEach((items) => {
        if (items.u_milestone_phid == args[0].u_milestone_phid) {
          args[0].u_plan_end_dt = items.u_plan_end_dt;
          if (!args[0].u_plan_dt) {
            console.log(`调试检测`,reduceDate(items.u_plan_end_dt,args[0].u_hkzq));
            args[0].u_plan_dt = reduceDate(items.u_plan_end_dt,args[0].u_hkzq)
          }
          instance.updateRow(args[0]);
        }
      });
    }, "p_form_Milestone_Repay_d.u_milestone_phid");
    useUpdateRows(({ args }) => {
      args[0].forEach((item) => {
        if (item.u_milestone_phid) {
          try {
            $NG.execServer("getMilestoneByPhid", { phid: item.u_milestone_phid }, function (res) {
              if (res) {
                const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                console.log(data);
                if (res.count > 0) {
                  item.u_phase = data.u_phase;
                  item.u_milestone_no = data.u_milestone_no;
                  item.u_milestone_name = data.u_milestone_name;
                } else {
                  console.log("功能扩展暂无数据");
                }
              } else {
                console.log("功能扩展报错");
              }
              dgrid3.refreshView();
            });
          } catch (error) {
            console.error("功能扩展报错:", error);
          }
        }
      });
    }, "p_form_Milestone_Repay_d");
  }

  //////////////////////////////////////////////////--dgrid4 p_form_Construction_plan 施工计划

  // 施工工序过滤 显示标准施工工序和该项目的施工工序

  //根据工作单元ID获取工作单元清单
  useDataIndexChange(({ args, instance }) => {
    $NG.execServer("getGzdyqdByPhid", { phid: args[0].u_gzdy_name }, function (res) {
      console.log("功能扩展:getGzdyqdByPhid");
      try {
        data = JSON.parse(res.data)[0].extendObjects;
        args[0].u_gzdy_no = data.u_gzdy_code;
        instance.updateRow(args[0]);
      } catch (error) {
        console.log("功能扩展为空:getGzdyqdByPhid");
      }
    });
  }, "p_form_Construction_plan.u_gzdy_name");
  useUpdateRows(({ args }) => {
    args[0].forEach((item) => {
      if (item.u_milestone_phid) {
        $NG.execServer("getMilestoneByPhid", { phid: item.u_milestone_phid }, function (res) {
          try {
            const data = JSON.parse(res.data)[0].extendObjects; //单返回值
            item.u_milestone_no = data.u_milestone_no;
            dgrid4.refreshView();
          } catch (error) {
            console.log("功能扩展报错", error);
          }
        });
      }
    });
  }, "p_form_Construction_plan");
  ////////////////////////////////////////////////////////////--dgrid4 function--////////////////////////////////////////////////////////////

  function dgrid4Filter() {
    const phid_pcV = mstform.getItem("phid_pc").getValue();
    const _Array = ["u_sggx_name"];
    _Array.forEach((item) => {
      $NG.updateUI((updater) => {
        if (updater.editGrid.p_form_Construction_plan[item]) {
          updater.editGrid.p_form_Construction_plan[item].setProps({
            clientSqlFilter: "m.u_is_standard ='1' or m.phid_pc = " + phid_pcV, //过滤条件
          });
        }
      });
    });
  }
  function addConstructionPlan() {
    if (!mstform.getItem("phid_pc").getValue()) {
      $NG.alert("请先选择项目");
      return;
    }
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "v_gzdyqd",
        valueField: "phid_gzdy",
        labelField: "gzdy_name",
        clientSqlFilter: `phid_pc= ${mstform.getItem("phid_pc").getValue()}`,
      })
      .then((data) => {
        try {
          if (Array.isArray(data) && data.length > 0) {
            var gridArr = [];
            for (var i = 0; i < data.length; i++) {
              var gridObj = {};
              // gridObj.rel_key1 = data[i].origin.phid;
              gridObj.u_gzdy_no = data[i].origin.gzdy_code || "";
              gridObj.u_gzdy_name = data[i].origin.phid_gzdy || "";
              gridObj.u_gzdy_name_EXName = data[i].origin.gzdy_name || "";
              gridObj.u_sggx_name = data[i].origin.process_id || "";
              gridObj.u_sggx_name_EXName = data[i].origin.process_name || "";
              gridObj.u_sggx_on = data[i].origin.process_code || "";
              gridArr.push(gridObj);
            }
            console.log(gridArr);
            dgrid4.addRows(gridArr);
            dgrid4.refreshView();
          } else {
            console.error("返回的数据无效或为空:", data);
          }
        } catch (error) {
          console.error("处理数据时出错:", error);
        }
      })
      .catch((error) => {
        console.error("打开NGHelp时发生错误:", error);
      });
  }
  ////////////////////////////////////////////////////////////--useUpdateRows--////////////////////////////////////////////////////////////
  // useUpdateRows(({ args }) => {
  //   const fields = ["u_current_month", "u_current_month_add1", "u_current_month_add2", "u_current_month_add3", "u_year_addmonth01", "u_year_addmonth02", "u_year_addmonth03", "u_year_addmonth04", "u_year_addmonth05", "u_year_addmonth06", "u_year_addmonth07", "u_year_addmonth08", "u_year_addmonth09", "u_year_addmonth10", "u_year_addmonth11", "u_year_addmonth12", "u_no_to_amt"];
  //   let fieldSums = {};
  //   fields.forEach((field) => {
  //     fieldSums[field] = 0;
  //   });

  //   args[0].forEach((item) => {
  //     if (parseInt(item.u_no_to_type) <= 7) {
  //       fields.forEach((field) => {
  //         fieldSums[field] += parseFloat(item[field]) || 0;
  //       });
  //     }
  //   });
  //   //合计前置数据到合计行
  //   args[0].forEach((item) => {
  //     if (item.u_no_to_type === "91") {
  //       fields.forEach((field) => {
  //         item[field] = fieldSums[field]; // Set the field to its cumulative sum
  //       });
  //     }

  //     // 合计每一行的数据到合计列
  //     let rowSum = 0;
  //     fields.forEach((field) => {
  //       rowSum += parseFloat(item[field]) || 0;
  //     });
  //     item.u_amt = rowSum;
  //   });

  //   dgrid6.refreshView();
  // }, "p_form_Unconverted_Income");
  let timeId = 0;
  useUpdateRows(({ args }) => {
    if (page.oType == "add" || page.oType == "edit")
      if (timeId != 0) {
        clearTimeout(timeId);
        timeId = 0;
      }
    //   timeId = setTimeout(() => {
    //     console.log(`监听`);
    //     try {
    //       const _arr = args[0];
    //       const currentCheck = dgrid1.getSelectedData()[0];
    //       const dateC = calculateDateDifference(currentCheck.u_plan_end_dt, currentCheck.u_plan_start_dt);
    //       console.log(dateC);
    //       _arr.forEach((item) => {
    //         switch (item.u_standardtype) {
    //           case "2":
    //             item.u_plan_start_dt = addDaysToDate(currentCheck.u_act_end_dt, Number(item.u_intervaltime) || 0);
    //             break;
    //           case "3":
    //             item.u_plan_start_dt = addDaysToDate(currentCheck.u_plan_start_dt, Number(item.u_intervaltime) || 0);
    //             break;
    //           case "4":
    //             item.u_plan_start_dt = addDaysToDate(currentCheck.u_plan_end_dt, Number(item.u_intervaltime) || 0);
    //             break;
    //         }
    //         item.u_plan_end_dt = addDaysToDate(item.u_plan_start_dt, Number(dateC) || 0);
    //       });
    //     } catch (err) {
    //     } finally {
    //       dgrid2.refreshView();
    //       timeId = 0;
    //     }
    //   }, 500);
  }, "p_form_Milestone_Task_d");

  ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////

  function mstformUpdateUI(params) {
    console.log("mstformUpdateUI");
    const disabled = ["u_ywlx", "u_division", "u_wbs_type", "u_xmjl"];
    const required = ["u_report_dt", "phid_pc"];
    const hidden = ["u_wbs_type"];
    $NG.updateUI((updater) => {
      const form = updater.form.p_form_Milestone_Plan_m;
      if (form) {
        disabled.forEach((item) => {
          if (form[item]) {
            form[item].setProps({ disabled: true });
          }
        });
        required.forEach((item) => {
          if (form[item]) {
            form[item].setProps({ required: true });
          }
        });
        hidden.forEach((item) => {
          if (form[item]) {
            form[item].setProps({ hidden: true });
          }
        });
      }
    });
  }

  function getPtInfoByPhid() {
    if (!mstform) return;
    if (mstform.getItem("phid_pc").getValue()) {
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;

        mstform.getItem("u_xmjl").setValue({
          value: datas.project_manager_phid,
          label: datas.project_manager_name,
        });

        // 二级部门
        mstform.getItem("phid_org").setValue({
          value: datas.org_phid,
          label: datas.org_name,
        });

        // 事业部
        mstform.getItem("u_division").setValue({
          value: datas.division_phid,
          label: datas.division_name,
        });

        console.log(datas.type_name);
        console.log(datas.type_phid);

        $NG.updateState((updater) => {
          updater.data.p_form_Milestone_Plan_m.setProps({
            //项目类型
            u_wbs_type: { value: datas.type_phid, label: datas.type_name },
          });
        });

        $NG.updateState((updater) => {
          updater.data.p_form_Milestone_Plan_m.setProps({
            //项目业务类型
            u_ywlx: { value: datas.user_ywlx, label: datas.ywlx_name },
          });
        });
        $NG.updateUI((updater) =>
          updater.editGrid.p_form_Construction_plan.u_gzdy_name.setProps((p) => {
            return {
              ...p,
              editor: {
                ...p.editor,
                clientSqlFilter: `m.phid_pc='${mstform.getItem("phid_pc").getValue() || 0}'`,
              },
            };
          })
        );
        if (String(datas.user_ywlx) == "8570000000000355") {
          console.log("user_ywlx:8570000000000355");
          $NG.updateUI((updater) => {
            updater.editGrid.p_form_Milestone_Repay_d.u_milestone_phid.setProps({
              clientSqlFilter: `u_wbs_type is null`,
            });
          });
          $NG.updateUI((updater) => {
            updater.editGrid.p_form_Construction_plan.u_milestone_phid.setProps({
              clientSqlFilter: `u_wbs_type is null`,
            });
          });
        } else {
          $NG.updateUI((updater) => {
            updater.editGrid.p_form_Milestone_Repay_d.u_milestone_phid.setProps({
              clientSqlFilter: `u_wbs_type= ${datas.type_phid}`,
            });
          });
          $NG.updateUI((updater) => {
            updater.editGrid.p_form_Construction_plan.u_milestone_phid.setProps({
              clientSqlFilter: `u_wbs_type= ${datas.type_phid}`,
            });
          });
        }
      });
    }
  }

  // function dgrid6UpdateUI(params) {
  //   $NG.updateUI((updater) => {
  //     let currentDate = new Date(mstform.getValues().u_report_dt || new Date());
  //     let dateFields = [];
  //     for (let i = 0; i < 16; i++) {
  //       year = currentDate.getFullYear();
  //       month = currentDate.getMonth() + 1; // getMonth() 返回 0-11，所以加 1
  //       let field = `${year}年${month}月`;
  //       dateFields.push(field);
  //       currentDate.setMonth(currentDate.getMonth() + 1);
  //     }
  //     const fields = ["u_current_month", "u_current_month_add1", "u_current_month_add2", "u_current_month_add3", "u_year_addmonth01", "u_year_addmonth02", "u_year_addmonth03", "u_year_addmonth04", "u_year_addmonth05", "u_year_addmonth06", "u_year_addmonth07", "u_year_addmonth08", "u_year_addmonth09", "u_year_addmonth10", "u_year_addmonth11", "u_year_addmonth12"];
  //     fields.forEach((field, index) => {
  //       updater.editGrid.p_form_Unconverted_Income[field].setProps({
  //         header: dateFields[index],
  //       });
  //     });
  //   });
  // }
  function dgrid6AddRows(params) {
    dgrid6.addRows([{ u_no_to_type: "1" }, { u_no_to_type: "2" }, { u_no_to_type: "3" }, { u_no_to_type: "4" }, { u_no_to_type: "5" }, { u_no_to_type: "6" }, { u_no_to_type: "7" }, { u_no_to_type: "91" }, { u_no_to_type: "92" }, { u_no_to_type: "93" }, { u_no_to_type: "94" }]);
  }

  function filter_help(table, key, d = "rel_key1") {
    //遍历表格
    let str = "";
    const _arr = table.getRows();
    console.log(_arr);
    const _is = [];
    _arr.forEach((item) => {
      _is.push(String(item[d]));
    });
    if (_is.length == 0) {
    } else {
      str = `and ${key} not in (`;
      _is.forEach((item, index) => {
        if (index > 0) {
          str += `,'${item}'`;
        } else {
          str += `'${item}'`;
        }
      });
      str += ")";
    }
    console.log(str);
    return str;
  }
  function addMilestone() {
    if (!mstform.getItem("phid_pc").getValue()) {
      $NG.alert("请先选择项目");
      return;
    }
    if (!mstform.getItem("u_division").getValue()) {
      $NG.alert("项目信息中事业部为空，请先维护项目事业部信息");
      return;
    }
    if (mstform.getItem("u_ywlx").getValue() == "8570000000000355") {
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "view_Task_Templates_d",
          valueField: "phid",
          labelField: "u_milestone_name",
          clientSqlFilter: `u_division IS NULL OR u_division = '' ${filter_help(dgrid1, "phid")}`,
        })
        .then((data) => {
          try {
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = data[i].origin.phid;
                gridObj.u_phase = data[i].origin.u_phase || "";
                gridObj.u_milestone_no = data[i].origin.u_milestone_no || "";
                gridObj.u_milestone_name = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_phid = data[i].origin.phid || "";
                gridObj.u_milestone_phid_EXName = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_type = data[i].origin.u_milestone_type_id;
                gridObj.u_milestone_type_EXName = data[i].origin.u_milestone_type_name || "";
                gridObj.u_start_dt = data[i].origin.u_start_dt || "";
                gridObj.u_end_dt = data[i].origin.u_end_dt || "";
                gridArr.push(gridObj);
              }
              console.log("addMilestone gridArr:");
              console.log(gridArr);
              dgrid1.addRows(gridArr);
              dgrid1.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    } else {
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "view_Task_Templates_d",
          valueField: "phid",
          labelField: "u_milestone_name",
          clientSqlFilter: `u_division= ${mstform.getItem("u_division").getValue()} ${filter_help(dgrid1, "phid")}`,
        })
        .then((data) => {
          try {
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = data[i].origin.phid;
                gridObj.u_phase = data[i].origin.u_phase || "";
                gridObj.u_milestone_no = data[i].origin.u_milestone_no || "";
                gridObj.u_milestone_name = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_phid = data[i].origin.phid || "";
                gridObj.u_milestone_phid_EXName = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_type = data[i].origin.u_milestone_type_id;
                gridObj.u_milestone_type_EXName = data[i].origin.u_milestone_type_name || "";
                gridObj.u_start_dt = data[i].origin.u_start_dt || "";
                gridObj.u_end_dt = data[i].origin.u_end_dt || "";
                gridArr.push(gridObj);
              }
              console.log("addMilestone gridArr:");
              console.log(gridArr);
              dgrid1.addRows(gridArr);
              dgrid1.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
  }
  function addMilestoneTaskClick() {
    if (!dgrid1.getSelectedData()[0]) {
      $NG.alert("请先选择对应的里程碑");
      return;
    }
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "Task_Templates_dd",
        valueField: "dd.phid",
        labelField: "dd.deliverables",
        clientSqlFilter: "m.u_division = " + mstform.getItem("u_division").getValue() + " and d.u_milestone_no='" + dgrid1.getSelectedData()[0].u_milestone_no + "'" + filter_help(dgrid2, "dd.u_deliverables", "u_deliverables"),
      })
      .then((data) => {
        try {
          // console.log(data);
          if (Array.isArray(data) && data.length > 0) {
            var gridArr = [];
            // console.log(data.length);
            for (var i = 0; i < data.length; i++) {
              var gridObj = {};
              gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
              gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
              gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
              gridObj.u_deliverables = data[i].origin.u_deliverables;
              gridObj.phid_emp = mstform.getItem("u_xmjl").getValue();
              gridObj.phid_emp_EXName = mstform.getItem("u_xmjl").getText();
              gridObj.u_deliverable_type = data[i].origin.u_deliverable_type;
              gridObj.u_busid = data[i].origin.u_busid;
              gridObj.u_busid_EXName = data[i].origin.busname || "";
              gridObj.u_standardtype = data[i].origin.u_standardtype;
              gridObj.u_intervaltime = data[i].origin.u_intervaltime;
              gridObj.u_isneed = data[i].origin.u_isneed;
              gridObj.u_donepoint = data[i].origin.u_donepoint;
              gridObj.u_sendmsg = data[i].origin.u_sendmsg;
              gridArr.push(gridObj);
            }
            console.log("addMilestoneTask gridArr:");
            console.log(gridArr);
            dgrid2.addRows(gridArr);
            dgrid2.refreshView();
          } else {
            console.error("返回的数据无效或为空:", data);
          }
        } catch (error) {
          console.error("处理数据时出错:", error);
        }
      })
      .catch((error) => {
        console.error("打开NGHelp时发生错误:", error);
      });
  }
  function addRepayTask() {
    if (!dgrid1.getSelectedData()[0]) {
      $NG.alert("请先选择对应的里程碑");
      return;
    }

    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "p_form_payment_plan_d",
        valueField: "d.phid",
        labelField: "d.u_hklcb",
        clientSqlFilter: "m.phid_pc = " + mstform.getItem("phid_pc").getValue() + filter_help(dgrid2, "d.u_hklcb", "u_fund_name"),
      })
      .then((data) => {
        try {
          // console.log(data);
          if (Array.isArray(data) && data.length > 0) {
            var gridArr = [];
            // console.log(data.length);
            for (var i = 0; i < data.length; i++) {
              var gridObj = {};
              gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
              gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
              gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
              gridObj.u_deliverables = "回款任务";
              gridObj.u_deliverable_type = "1";
              gridObj.u_busid = 77;
              gridObj.u_busid_EXName = "承包合同收款";
              gridObj.u_standardtype = "4";
              gridObj.u_intervaltime = "";
              gridObj.u_isneed = "2";
              gridObj.u_donepoint = "2";
              gridObj.u_sendmsg = "1";
              gridObj.u_fund_name = data[i].origin.u_hklcb;
              gridObj.amt = data[i].origin.u_hk_amt;
              gridArr.push(gridObj);
            }
            console.log("addRepayTask gridArr:");
            console.log(gridArr);
            dgrid2.addRows(gridArr);
            dgrid2.refreshView();
          } else {
            console.error("返回的数据无效或为空:", data);
          }
        } catch (error) {
          console.error("处理数据时出错:", error);
        }
      })
      .then(() => {
        try {
          setTimeout(function () {
            updateRepay();
          }, 500);
        } catch (error) {
          console.error("调用 updateRepay 时发生错误:", error);
        }
      })
      .catch((error) => {
        console.error("打开NGHelp时发生错误:", error);
      });
  }
  //新增回款明细
  function addRepayPlan() {
    if (dgrid3 && mstform.getItem("phid_pc").getValue()) {
      dgrid3.clearRows();
      $NG.execServer("getPaymentPlanByPhid_pc", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        console.log("getPaymentPlanByPhid_pc");
        console.log(res.data);
        var gridArr = [];
        var gridCount = res.count;
        for (var i = 0; i < gridCount; i++) {
          var gridObj = {};
          //对表体字段进行赋值,可以取数据库中的值进行赋值
          gridObj.u_fund_name = data[i].extendObjects.u_hklcb;
          gridObj.amt = data[i].extendObjects.u_hk_amt;
          gridObj.u_hkzq = data[i].extendObjects.u_hkzq;
          gridObj.u_receivable_dt = data[i].extendObjects.u_hk_dt;
          gridArr.push(gridObj);
        }
        //调用新增表体行数据的函数
        dgrid3.addRows(gridArr);
      });
    }
  }

  function updateRepay(params) {
    var selectedData = dgrid1.getSelectedData()[0] || {};
    var rel_key1 = selectedData.rel_key1 || "";
    // var u_phase = selectedData.u_phase || "";
    // var u_milestone_no = selectedData.u_milestone_no || "";
    // var u_milestone_name = selectedData.u_milestone_name || "";
    var u_plan_start_dt = selectedData.u_plan_start_dt || "";
    var u_plan_end_dt = selectedData.u_plan_end_dt || "";
    console.log(`事件编辑`, params);
    const el = params[0];
    if (isDate(u_plan_start_dt, el.u_plan_start_dt)) {
      $NG.alert("时间不能早于里程碑开始时间！");
      el.u_plan_start_dt = u_plan_start_dt;
    }
    if (isDate(el.u_plan_end_dt, u_plan_end_dt)) {
      $NG.alert("时间不能晚于里程碑结束时间！");
      el.u_plan_end_dt = u_plan_end_dt;
    }
    // 用于存储 dgrid2 中符合条件的 u_fund_name
    var fundNames = [];
    // 遍历 dgrid2，找到 rel_key1 相等的行并记录 u_fund_name
    dgrid2.getRows().forEach(function (item) {
      if (item.rel_key1 === rel_key1) {
        if (!item.u_plan_start_dt) {
          item.u_plan_start_dt = u_plan_start_dt;
        }
        if (!item.u_plan_end_dt) {
          item.u_plan_end_dt = u_plan_end_dt;
        }
        console.log(`项目匹配`, item.rel_key1, rel_key1);
      }
    });
    // 遍历 dgrid3，更新符合条件的行的 u_plan_dt
    dgrid2.refreshView();
    dgrid3.refreshView();
  }
  // 日期格式化
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      case "YYYYmmDD":
        formattedDate = `${year}${month.padStart(2, "0")}${day.padStart(2, "0")}`;
        break;
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
  // 表体插入重复数据的检测方法
  function insertIfNotExists(data) {
    // 获取当前表体的所有行
    const existingRows = $NG.getCmpApi("p_form_Milestone_Task_d").getRows();
    // 创建一个Map来快速查找u_htzjxx
    const existingRowsMap = new Map(existingRows.map((row) => [row.u_htzjxx, true]));

    // 收集需要插入的新行（这里假设我们直接插入整个data对象，但您可能只需要部分）
    const newRows = [];

    data.forEach((item) => {
      // 检查该item的origin.phid是否已在existingRows中
      if (!existingRowsMap.has(item.origin.phid)) {
        // 如果不存在，则添加到newRows中（这里以整个item为例）
        newRows.push(item);

        // 注意：如果您只想插入部分数据，请在这里进行修改
        // 例如：newRows.push({ /* 仅包含您想插入的字段 */ });
      }
      // 如果存在，则不执行任何操作，因为不需要插入
    });

    // 现在，newRows包含了所有需要插入的行
    // 接下来，您可能需要调用另一个API或函数来实际执行插入操作
    // 假设有一个函数叫做 insertRows，它接受一个数组并插入到表体中
    // insertRows(newRows); // 这需要您自己实现或调用现有的API

    // 注意：这里我没有实现insertRows函数，因为它将依赖于您的具体API或框架
    console.log("需要插入的数组对象:", newRows); // 仅用于演示
    return newRows;
  }
  function addDaysToDate(dateString, daysToAdd) {
    if (!dateString) return "";
    // 将日期字符串转换为 Date 对象
    let date = new Date(dateString);

    // 增加天数
    date.setDate(date.getDate() + daysToAdd);

    // 获取新的日期并格式化成 YYYY-MM-DD 格式
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以加1
    let day = date.getDate().toString().padStart(2, "0");

    return `${year}-${month}-${day}`;
  }
  function calculateDateDifference(date1, date2) {
    if (!date1 || !date2) return "";
    // 将日期字符串转换为 Date 对象
    let d1 = new Date(date1);
    let d2 = new Date(date2);

    // 计算两个日期的差值（以毫秒为单位）
    let timeDifference = Math.abs(d2 - d1);

    // 转换为天数
    let dayDifference = timeDifference / (1000 * 3600 * 24);

    return dayDifference;
  }
  //事件判断
  function isDate(date1, date2) {
    const d1 = new Date(date1).getTime();
    const d2 = new Date(date2).getTime();
    console.log(d1, d2, date1, date2);
    return d1 - d2 > 0;
  }
  // 示例调用
});
